package com.br.fmn.clubedoimovel.negocio.servico;

import java.io.IOException;

import android.location.Geocoder;

import com.br.fmn.clubedoimovel.negocio.entidade.PlaceEntity;
import com.br.fmn.clubedoimovel.negocio.entidade.PlaceGeometry;
import com.br.fmn.clubedoimovel.negocio.entidade.PlaceGeometry.PlaceLocation;
import com.br.fmn.clubedoimovel.negocio.entidade.PlacesAutocompleteList;
import com.google.android.maps.GeoPoint;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;

public class PlaceService {

	private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
	private static final String PLACES_GEOCODE_URL = "http://maps.googleapis.com/maps/api/geocode/json?";

	private static final HttpTransport transport = new ApacheHttpTransport();

	public PlacesAutocompleteList performAutoComplete(String reference)
			throws IOException {

		HttpRequestFactory httpRequestFactory = ConnectionManager
				.createRequestFactory(transport);

		HttpRequest request = httpRequestFactory
				.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));

		request.url.put("input", reference);
		request.url.put("types", PlaceEntity.TYPE);
		request.url.put("region", PlaceEntity.REGION);
		request.url.put("language", PlaceEntity.LANGUAGE);
		request.url.put("sensor", PlaceEntity.SENSOR);
		request.url.put("key", PlaceEntity.PLACE_KEY);

		PlacesAutocompleteList places = request.execute().parseAs(
				PlacesAutocompleteList.class);

		return places;

	}

	public PlaceLocation performLocation(String reference) throws IOException {

		HttpRequestFactory httpRequestFactory = ConnectionManager
				.createRequestFactory(transport);

		HttpRequest request = httpRequestFactory
				.buildGetRequest(new GenericUrl(PLACES_GEOCODE_URL));

		request.url.put("address", reference);
		request.url.put("sensor", PlaceEntity.SENSOR);

		PlaceLocation geocodes = request.execute().parseAs(PlaceLocation.class);

		return geocodes;

	}
}
